package com.pengyang.netty.demo.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

import com.pengyang.netty.demo.pojo.IMMessage;
import com.pengyang.netty.demo.pojo.SelfDefinedProtocol;
import com.pengyang.netty.demo.server.ServerHandler;
import com.pengyang.netty.demo.util.SelfDefinedDecoder;
import com.pengyang.netty.demo.util.SelfDefinedEncoder;

import io.netty.bootstrap.Bootstrap;  
import io.netty.channel.ChannelFuture;  
import io.netty.channel.ChannelInitializer;  
import io.netty.channel.ChannelOption;  
import io.netty.channel.EventLoopGroup;  
import io.netty.channel.nio.NioEventLoopGroup;  
import io.netty.channel.socket.SocketChannel;  
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;  
  
public class Client  implements Runnable,IMClientConfig {  
  
	 private   ClientHandler clientHandler = new ClientHandler();
	 
	 @Override
	    public void run() {
	        EventLoopGroup workerGroup = new NioEventLoopGroup();
	        try {
	            Bootstrap b = new Bootstrap();
	            b.group(workerGroup)
	                .channel(NioSocketChannel.class)
	                .option(ChannelOption.SO_KEEPALIVE, true)
	                .handler(new ChannelInitializer<SocketChannel>() {
	                @Override
	                public void initChannel(SocketChannel ch) throws Exception {
	                    ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(65536, 0, 2, 0, 2));
	                    ch.pipeline().addLast("msgpack decoder",new SelfDefinedDecoder());
	                    ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(2));
	                    ch.pipeline().addLast("msgpack encoder",new SelfDefinedEncoder());
	                    ch.pipeline().addLast(clientHandler);
	                }
	            });
	            ChannelFuture f = b.connect(SERVER_HOST, SERVER_PORT).sync();
	            f.channel().closeFuture().sync();
	        } catch (InterruptedException e) {
	            e.printStackTrace();
	        } finally {
	            workerGroup.shutdownGracefully();
	        }
	    }
	 
	 public void runClientCMD(IMMessage message) throws IOException{
		 clientHandler.setMsg(message);
	 }
	 
	 public void start(IMMessage message) throws IOException{
	        new Thread(this).start();
	        runClientCMD(message);
	 }
	 
	 public static void main(String[] args) throws IOException{
		 IMMessage message = new IMMessage(
	               8888,
	               TYPE_MSG_TEXT.value(),
	               9999,
	               "你好啊，9999"
	               );
	        new Client().start(message);
	 }

}  
